package com.cll.prototype.user.controller;


import com.cll.prototype.common.dictionary.AjaxResultEnum;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.api.user.service.ILoginTokenService;
import com.cll.prototype.api.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 用户登录成功之后的令牌（token）表 前端控制器
 * </p>
 *
 * @author CLL
 * @since 2020-10-26
 */
@RestController
@RequestMapping("/login_token")
public class LoginTokenController {

    private static final Logger logger = LoggerFactory.getLogger(LoginTokenController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginTokenService loginTokenService;

    /**
     * 用户登录
     * @param email 邮箱
     * @param password  密码
     * @return  登录结果.登录成功之后，生成token，存放到数据库中，并写入cookie中
     */
    @PostMapping(value = "/login")
    public AjaxResult login(@RequestParam("email") String email,
                            @RequestParam("password") String password,
                            HttpServletResponse response){
        try {
            AjaxResult loginResult = userService.login(email, password);
            if (null != loginResult && AjaxResultEnum.SUCCESS.getCode() == loginResult.getCode() && null != loginResult.getData()) {
                Cookie cookie = new Cookie("token", loginResult.getData().toString());
                response.addCookie(cookie);
            }
            return loginResult;
        } catch (Exception e) {
            logger.error("****** 用户登录抛出异常" + e.getMessage(), e);
            return AjaxResult.error(55, "用户登录抛出异常");
        }
    }

    /**
     * 根据令牌获取用户邮箱号
     * @param token 令牌
     * @return  获取结果
     */
    @PostMapping(value = "/getEmailByToken")
    public AjaxResult getEmailByToken(@RequestParam("token") String token){
        try {
            return loginTokenService.getEmailByToken(token);
        } catch (Exception e) {
            logger.error("****** 根据token获取用户信息抛出异常" + e.getMessage(), e);
            return AjaxResult.error(51, "获取用户信息失败");
        }
    }

}